#include "logfile.h"

using namespace tiny_muduo;

LogFile::LogFile(const char* filepath=nullptr)
    :fp_(::fopen(filepath,"ae")),
     written_bytes_(0),
     lastwrite_(0),
     lastflush_(0){
        if(!fp_){
            std::string DefaultPath=std::move("./LogFile_"+
                          Timestamp::Now().Timestamp::ToFormattedDefaultString()+
                          ".log");
            fp_=::fopen(DefaultPath.data(),"ae");              
        }
     }

 LogFile::~LogFile(){
     Flush();
     fclose(fp_);
}

void LogFile::Write(const char* data,int len){
    int pos=0;
    while(pos!=len){
        pos+=fwrite_unlocked(data+pos,sizeof(char),len-pos,fp_);
    // fwrite_unlocked 函数，这是 POSIX 标准定义的一个非阻塞的写入函数，适用于在多线程环境中进行文件写入操作
    }
    time_t now=::time(nullptr);
    if(len!=0){
        lastwrite_=now;
        written_bytes_+=len;
    }
    if(lastwrite_-lastflush_ > kFlushInterval){
        Flush();
        lastflush_=now;
    }
    //到一定时间间隔会定时将缓冲区内容放入文件中并清空缓冲区
}
